<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>
  <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" :label-width="100">
  <el-form-item label="姓名" prop="name">
      <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="phone">
      <el-input v-model="dataForm.phone" placeholder="电话"></el-input>
  </el-form-item>
  <el-form-item label="省" prop="province">
      <el-input v-model="dataForm.province" placeholder="省"></el-input>
  </el-form-item>
  <el-form-item label="市" prop="city">
      <el-input v-model="dataForm.city" placeholder="市"></el-input>
  </el-form-item>
  <el-form-item label="区/县" prop="district">
      <el-input v-model="dataForm.district" placeholder="区/县"></el-input>
  </el-form-item>
  <el-form-item label="详细地址" prop="address">
      <el-input v-model="dataForm.address" placeholder="详细地址"></el-input>
  </el-form-item>
  <el-form-item label="备注" prop="remark">
      <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
  </el-form-item>
  </el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
// 只导入实际存在的 API 方法
import { useTestInfoApi, useTestInfoSubmitApi } from '@/api/user/info'

const emit = defineEmits(['refreshDataList'])

const visible = defineModel<boolean>('visible')
const dataFormRef = ref()

const dataForm = reactive({
	id: '',
	name: '',
	phone: '',
	province: '',
	city: '',
	district: '',
	address: '',
	remark: '',
	createTime: '',
	updateTime: ''})

const init = (id?: number) => {
	if (id) {
		getInfo(id)
	}
}

const getInfo = (id: number) => {
  // res 参数加 any 类型注解，实际可根据后端返回类型细化
  useTestInfoApi(id).then((res: any) => {
    Object.assign(dataForm, res.data)
  })
}

const dataRules = ref({
	name: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	phone: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	province: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	city: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	district: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	address: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	remark: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]})

// 表单提交
const submitHandle = () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return false
    }
    // 提交表单，调用实际存在的 API
    useTestInfoSubmitApi(dataForm).then(() => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          visible.value = false
          emit('refreshDataList')
        }
      })
    })
  })
}

defineExpose({
	init
})
</script>
